<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>计算器</title>
</head>

<body>
  <h1>这是一个很强大的计算器</h1>
  <div id="inputArea">
    <input type="text" id="number1" />
    <select id="operator">
      <option value="0">加</option>
      <option value="1">减</option>
      <option value="2">乘</option>
      <option value="3">除</option>
    </select>
    <input type="text" id="number2" />
  </div>

  <input type="button" onClick="caculateOpt()" value="点我啊" />

  <h2 id="showResult">请输入数字并选择符号，点击计算按钮即可获得结果！！</h2>

  <script>
    var num1, num2, opt, result, optStr;
    var colorhead = '<font color="#0099ff">';
    var colorfoot = "</font>";
    var errorMsg1 = "请输入正确格式的数字！！";
    var errorMsg2 = "您正在做除法，小学数学老师没教你除数不能为0吗？？！！";

    function caculateOpt() {

      var1 = document.getElementById("number1").value;
      var2 = document.getElementById("number2").value;

      opt = document.getElementById("operator").value;

      var yanzhengInput = valInput(var1, var2);

      if (yanzhengInput) {
        num1 = parseFloat(var1);
        num2 = parseFloat(var2);
        switch (opt) {
          case "0":
            result = num1 + num2;
            optStr = "加上";
            break;
          case "1":
            result = num1 - num2;
            optStr = "减去";
            break;
          case "2":
            result = num1 * num2;
            optStr = "乘以";
            break;
          case "3":
            result = num1 / num2;
            optStr = "除以";
            break;
        }
        document.getElementById("showResult").innerHTML =
          colorhead + num1 + optStr + num2 + "的结果是:" + result + colorfoot;
      }
    }

    function valInput(var1, var2) {

      if (isNaN(var1) || isNaN(var2)) {
        alert(errorMsg1);
        colorhead = '<font color="#ff0000">';
        document.getElementById("showResult").innerHTML =
          colorhead + errorMsg1 + colorfoot;
        return false;

      } else if (opt == "3" && var2 == 0) {
        alert(errorMsg2);
        colorhead = '<font color="#ff0000">';
        document.getElementById("showResult").innerHTML =
          colorhead + errorMsg2 + colorfoot;
        return false;
      } else {
        var colorhead = '<font color="#009900">';
        return true;
      }
    }
  </script>
</body>

</html>